<template>
  <div class="notification-page p-6">
    <!-- 页面标题和消息统计 -->
    <div class="page-header mb-6">
      <div class="header-left flex items-center gap-4">
        <h2 class="text-2xl font-bold text-gray-800 dark:text-white m-0">
          消息中心
        </h2>
        <div class="message-stats flex items-center text-sm">
          <span class="total-messages text-gray-600 dark:text-gray-400"
            >共 {{ totalMessages }} 条消息</span
          >
          <el-divider direction="vertical" class="mx-2 h-3.5" />
          <span
            class="unread-messages text-gray-600 dark:text-gray-400"
            v-if="totalUnread > 0"
          >
            <span
              class="number text-red-500 dark:text-red-400 font-semibold text-base mx-1"
              >{{ totalUnread }}</span
            >
            条未读
          </span>
        </div>
      </div>
      <div class="header-right">
        <el-space>
          <el-button plain @click="handleMarkAllRead">
            <el-icon><Check /></el-icon>
            全部已读
          </el-button>
        </el-space>
      </div>
    </div>

    <!-- 消息筛选和列表区域 -->
    <el-card shadow="hover" class="filter-card mb-6">
      <div class="filter-section">
        <el-form
          :model="filterForm"
          label-position="right"
          label-width="80px"
          size="default"
          class="filter-form"
        >
          <el-row :gutter="20">
            <el-col :span="8">
              <el-form-item label="时间范围">
                <el-date-picker
                  v-model="filterForm.timeRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"
                  class="w-full"
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="状态">
                <el-select v-model="filterForm.status" class="w-full">
                  <el-option label="全部" value="all" />
                  <el-option label="已读" value="read" />
                  <el-option label="未读" value="unread" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="类型">
                <el-select v-model="filterForm.type" class="w-full">
                  <el-option label="全部" value="all" />
                  <el-option label="订单通知" value="order" />
                  <el-option label="系统通知" value="system" />
                  <el-option label="提现通知" value="finance" />
                  <el-option label="客户通知" value="customer" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4" class="flex items-center justify-end">
              <el-button type="primary" @click="handleSearch">
                <el-icon><Search /></el-icon>
                查询
              </el-button>
              <el-button @click="resetFilter">
                <el-icon><RefreshLeft /></el-icon>
                重置
              </el-button>
            </el-col>
          </el-row>
        </el-form>
      </div>
    </el-card>

    <!-- 消息分类标签 -->
    <el-card shadow="hover" class="message-card">
      <div class="tabs-container">
        <el-tabs v-model="activeTab" @tab-click="handleTabChange">
          <el-tab-pane label="全部消息" name="all">
            <template #label>
              <span class="tab-title flex items-center">
                全部消息
                <el-badge
                  :value="totalUnread"
                  :hidden="totalUnread === 0"
                  class="ml-2"
                />
              </span>
            </template>
          </el-tab-pane>
          <el-tab-pane label="订单通知" name="order">
            <template #label>
              <span class="tab-title flex items-center">
                订单通知
                <el-badge
                  :value="orderUnread"
                  :hidden="orderUnread === 0"
                  class="ml-2"
                />
              </span>
            </template>
          </el-tab-pane>
          <el-tab-pane label="系统通知" name="system">
            <template #label>
              <span class="tab-title flex items-center">
                系统通知
                <el-badge
                  :value="systemUnread"
                  :hidden="systemUnread === 0"
                  class="ml-2"
                />
              </span>
            </template>
          </el-tab-pane>
          <el-tab-pane label="提现通知" name="finance">
            <template #label>
              <span class="tab-title flex items-center">
                提现通知
                <el-badge
                  :value="financeUnread"
                  :hidden="financeUnread === 0"
                  class="ml-2"
                />
              </span>
            </template>
          </el-tab-pane>
          <el-tab-pane label="客户通知" name="customer">
            <template #label>
              <span class="tab-title flex items-center">
                客户通知
                <el-badge
                  :value="customerUnread"
                  :hidden="customerUnread === 0"
                  class="ml-2"
                />
              </span>
            </template>
          </el-tab-pane>
        </el-tabs>
      </div>

      <!-- 消息列表 -->
      <el-table
        :data="paginatedMessages"
        stripe
        border
        highlight-current-row
        v-loading="loading"
        style="width: 100%"
        :row-class-name="getRowClass"
        @row-click="handleRowClick"
      >
        <el-table-column label="状态" width="80" align="center">
          <template #default="scope">
            <el-tag
              :type="scope.row.isRead ? 'info' : 'danger'"
              effect="plain"
              size="small"
            >
              {{ scope.row.isRead ? "已读" : "未读" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="类型" width="100" align="center">
          <template #default="scope">
            <el-tag
              :type="getTypeTagType(scope.row.type)"
              effect="light"
              size="small"
            >
              {{ getTypeLabel(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="250">
          <template #default="scope">
            <div
              class="message-title"
              :class="{ 'font-bold': !scope.row.isRead }"
            >
              {{ scope.row.title }}
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="content"
          label="内容"
          min-width="300"
          show-overflow-tooltip
        />
        <el-table-column prop="time" label="时间" width="180" align="center">
          <template #default="scope">
            {{ formatTime(scope.row.time) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="220" align="center" fixed="right">
          <template #default="scope">
            <div class="flex items-center space-x-2 justify-center">
              <el-button
                size="small"
                plain
                :disabled="scope.row.isRead"
                @click.stop="handleMarkRead(scope.row)"
              >
                标为已读
              </el-button>
              <el-button size="small" plain @click.stop="handleView(scope.row)">
                查看详情
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container flex justify-end mt-4">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :total="pagination.total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 通知详情对话框 -->
    <el-dialog
      v-model="dialogVisible"
      title="消息详情"
      :width="600"
      destroy-on-close
    >
      <template v-if="selectedMessage">
        <div class="message-detail">
          <div class="message-header mb-4">
            <h3 class="text-xl font-bold mb-2">{{ selectedMessage.title }}</h3>
            <div
              class="meta-info text-sm text-gray-500 flex items-center justify-between"
            >
              <div class="left-meta flex items-center gap-3">
                <el-tag
                  :type="getTypeTagType(selectedMessage.type)"
                  effect="light"
                  size="small"
                >
                  {{ getTypeLabel(selectedMessage.type) }}
                </el-tag>
                <span>{{ formatDetailTime(selectedMessage.time) }}</span>
              </div>
              <div class="right-meta">
                <el-tag
                  :type="selectedMessage.isRead ? 'info' : 'danger'"
                  effect="plain"
                  size="small"
                >
                  {{ selectedMessage.isRead ? "已读" : "未读" }}
                </el-tag>
              </div>
            </div>
          </div>
          <div
            class="message-content p-4 bg-gray-50 dark:bg-gray-800 rounded-lg mb-4"
          >
            <p class="whitespace-pre-line">{{ selectedMessage.content }}</p>
          </div>
          <div
            v-if="selectedMessage.actionUrl"
            class="action-area border-t border-gray-200 dark:border-gray-700 pt-4 mt-4"
          >
            <el-button
              type="primary"
              plain
              @click="handleAction(selectedMessage)"
            >
              <el-icon><Link /></el-icon>
              查看相关内容
            </el-button>
          </div>
        </div>
      </template>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-if="selectedMessage && !selectedMessage.isRead"
            @click="handleMarkRead(selectedMessage, true)"
          >
            标为已读
          </el-button>
          <el-button type="primary" @click="dialogVisible = false">
            关闭
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Check, Search, RefreshLeft, Link } from "@element-plus/icons-vue";
import dayjs from "dayjs";
import { useNotificationStore } from "@/stores/notification";
import axios from "@/api/axios";

const router = useRouter();
const notificationStore = useNotificationStore();
const loading = ref(false);
const dialogVisible = ref(false);
const selectedMessage = ref(null);
const activeTab = ref("all");

// 分页配置
const pagination = ref({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 筛选表单
const filterForm = ref({
  timeRange: [],
  status: "all",
  type: "all",
});

// 通知数据
const messages = ref([]);

// 模拟测试数据（备用）
const mockMessages = [
  {
    id: 1,
    type: "order",
    title: "新订单通知",
    content: "您有一个新的订单(#M20240315001)已付款，请及时处理。",
    time: new Date("2024-03-15 10:30:00"),
    isRead: false,
    actionUrl: "/merchant/orders",
  },
  {
    id: 2,
    type: "customer",
    title: "新客户评价",
    content: '客户"王女士"对您的商品"贵港特产礼盒"发表了评价，请查看。',
    time: new Date("2024-03-15 09:15:00"),
    isRead: false,
    actionUrl: "/merchant/comments",
  },
  {
    id: 3,
    type: "system",
    title: "系统维护通知",
    content:
      "系统将于2024年3月16日凌晨2:00-4:00进行例行维护，期间可能无法正常访问系统。请提前做好安排。",
    time: new Date("2024-03-14 14:00:00"),
    isRead: true,
  },
  {
    id: 4,
    type: "finance",
    title: "提现成功通知",
    content: "您申请的1500元提现已成功到账，请查收。",
    time: new Date("2024-03-13 16:20:00"),
    isRead: true,
    actionUrl: "/merchant/finance",
  },
  {
    id: 5,
    type: "finance",
    title: "提现申请已受理",
    content:
      "您的3000元提现申请已受理，预计1-2个工作日内到账，请留意账户变动。",
    time: new Date("2024-03-12 15:30:00"),
    isRead: false,
    actionUrl: "/merchant/finance",
  },
  {
    id: 6,
    type: "system",
    title: "账号安全提醒",
    content: "您的账号近期登录设备有变更，如非本人操作，请及时修改密码。",
    time: new Date("2024-03-11 08:45:00"),
    isRead: true,
    actionUrl: "/merchant/account/settings",
  },
];

// 计算属性
const totalMessages = computed(() => pagination.value.total || 0);
const totalUnread = computed(() => notificationStore.unreadCount.total);
const orderUnread = computed(() => notificationStore.unreadCount.order);
const systemUnread = computed(() => notificationStore.unreadCount.system);
const financeUnread = computed(() => notificationStore.unreadCount.finance);
const customerUnread = computed(() => notificationStore.unreadCount.customer || 0);

// 根据筛选条件和标签页过滤消息
const filteredMessages = computed(() => {
  let result = [...messages.value];

  // 按标签页筛选
  if (activeTab.value !== "all") {
    result = result.filter((m) => m.type === activeTab.value);
  }

  // 按状态筛选
  if (filterForm.value.status === "read") {
    result = result.filter((m) => m.isRead);
  } else if (filterForm.value.status === "unread") {
    result = result.filter((m) => !m.isRead);
  }

  // 按类型筛选
  if (filterForm.value.type !== "all") {
    result = result.filter((m) => m.type === filterForm.value.type);
  }

  // 按时间范围筛选
  if (filterForm.value.timeRange && filterForm.value.timeRange.length === 2) {
    const startDate = new Date(filterForm.value.timeRange[0]);
    const endDate = new Date(filterForm.value.timeRange[1]);
    endDate.setHours(23, 59, 59, 999); // 设置为当天结束时间

    result = result.filter((m) => {
      const messageDate = new Date(m.time);
      return messageDate >= startDate && messageDate <= endDate;
    });
  }

  // 按时间倒序排序
  result.sort((a, b) => new Date(b.time) - new Date(a.time));

  return result;
});

// 用于分页的消息
const paginatedMessages = computed(() => messages.value);

// 获取消息类型标签样式
const getTypeTagType = (type) => {
  const typeMap = {
    order: "success",
    system: "info",
    finance: "warning",
    customer: "primary",
  };
  return typeMap[type] || "info";
};

// 获取消息类型标签文本
const getTypeLabel = (type) => {
  const typeMap = {
    order: "订单通知",
    system: "系统通知",
    finance: "提现通知",
    customer: "客户通知",
  };
  return typeMap[type] || "其他通知";
};

// 格式化时间
const formatTime = (time) => {
  return dayjs(time).format("YYYY-MM-DD HH:mm");
};

// 格式化详细时间
const formatDetailTime = (time) => {
  return dayjs(time).format("YYYY-MM-DD HH:mm:ss");
};

// 获取行样式
const getRowClass = ({ row }) => {
  return !row.isRead ? "unread-row" : "";
};

// 获取通知列表
const fetchNotifications = async () => {
  loading.value = true;
  try {
    // 构造请求参数
    const params = {
      page: pagination.value.currentPage,
      pageSize: pagination.value.pageSize,
      type: filterForm.value.type !== "all" ? filterForm.value.type : undefined,
      status: filterForm.value.status !== "all" ? filterForm.value.status : undefined,
      startDate: filterForm.value.timeRange?.[0],
      endDate: filterForm.value.timeRange?.[1],
      tab: activeTab.value !== "all" ? activeTab.value : undefined,
    };

    // 调用API
    const response = await axios.get("/merchant/notifications", { params });
    if (response.data) {
      messages.value = response.data.list.map(item => ({
        ...item,
        time: new Date(item.time || item.createTime || item.create_time) // 兼容不同的时间字段
      }));
      pagination.value.total = response.data.total;
    }
  } catch (error) {
    console.error("获取通知列表失败:", error);
    // 使用测试数据
    messages.value = mockMessages;
    pagination.value.total = messages.value.length;
    ElMessage.warning("使用测试数据显示");
  } finally {
    loading.value = false;
  }
};

// 处理标签页切换
const handleTabChange = () => {
  pagination.value.currentPage = 1;
  fetchNotifications();
};

// 处理查询
const handleSearch = () => {
  pagination.value.currentPage = 1;
  fetchNotifications();
};

// 重置筛选条件
const resetFilter = () => {
  filterForm.value = {
    timeRange: [],
    status: "all",
    type: "all",
  };
  pagination.value.currentPage = 1;
  fetchNotifications();
};

// 处理分页大小变化
const handleSizeChange = (size) => {
  pagination.value.pageSize = size;
  fetchNotifications();
};

// 处理当前页变化
const handleCurrentChange = (page) => {
  pagination.value.currentPage = page;
  fetchNotifications();
};

// 处理行点击
const handleRowClick = (row) => {
  selectedMessage.value = row;
  dialogVisible.value = true;

  // 如果未读，标记为已读
  if (!row.isRead) {
    handleMarkRead(row);
  }
};

// 处理查看消息
const handleView = (message) => {
  selectedMessage.value = message;
  dialogVisible.value = true;

  // 如果未读，标记为已读
  if (!message.isRead) {
    handleMarkRead(message);
  }
};

// 标记单条消息为已读
const handleMarkRead = async (message, closeDialog = false) => {
  if (!message.isRead) {
    try {
      // 调用标记已读API
      await axios.put(`/merchant/notifications/${message.id}/read`);
      
      // 更新本地状态
      message.isRead = true;
      
      // 更新未读数量
      await notificationStore.fetchUnreadCount();
      
      ElMessage.success("已标记为已读");
      
      if (closeDialog) {
        dialogVisible.value = false;
      }
    } catch (error) {
      console.error("标记已读失败:", error);
      // 本地更新，失败时仍然更新本地状态
      message.isRead = true;
      ElMessage.warning("操作已在本地完成，但可能未同步到服务器");
    }
  }
};

// 标记全部为已读
const handleMarkAllRead = async () => {
  try {
    await ElMessageBox.confirm("确定要将所有消息标记为已读吗？", "提示", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "info",
    });

    try {
      // 调用标记全部已读API
      await axios.put("/merchant/notifications/read-all");
      
      // 更新本地状态
      messages.value.forEach((message) => {
        message.isRead = true;
      });
      
      // 更新未读数量
      await notificationStore.fetchUnreadCount();
      
      ElMessage.success("所有消息已标记为已读");
    } catch (error) {
      console.error("标记全部已读失败:", error);
      // 本地更新
      messages.value.forEach((message) => {
        message.isRead = true;
      });
      ElMessage.warning("操作已在本地完成，但可能未同步到服务器");
    }
  } catch {
    // 用户取消操作
  }
};

// 处理操作链接
const handleAction = (message) => {
  if (message.actionUrl) {
    router.push(message.actionUrl);
    dialogVisible.value = false;
  }
};

// 生命周期钩子
onMounted(async () => {
  loading.value = true;
  try {
    // 获取未读数量
    await notificationStore.fetchUnreadCount();
    
    // 获取通知列表
    await fetchNotifications();
    
    // 定期刷新未读数量
    const interval = setInterval(() => {
      notificationStore.fetchUnreadCount();
    }, 60000); // 每分钟刷新一次
    
    // 组件卸载时清除定时器
    return () => clearInterval(interval);
  } catch (error) {
    console.error("初始化通知中心失败:", error);
    ElMessage.error("加载通知数据失败");
  } finally {
    loading.value = false;
  }
});

// 监听标签页变化
watch(activeTab, () => {
  pagination.value.currentPage = 1;
  fetchNotifications();
});
</script>

<style scoped>
.notification-page {
  min-height: calc(100vh - 64px);
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.unread-row {
  background-color: rgba(245, 247, 250, 0.5);
}

.message-title {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

/* 暗黑模式适配 */
.dark .unread-row {
  background-color: rgba(38, 41, 45, 0.5);
}
</style>
